<template>
  <div>
    <a-input-search
      style="margin: 10px"
      placeholder="Search"
      @change="onChange"
    />
    <a-tree
      :checkable="checkable"
      :tree-data="sTreeData"
      :selected-keys="selectedKeys"
      :expanded-keys="expandedKeys"
      :multiple="multiple"
      :replace-fields="replaceFields"
      :auto-expand-parent="autoExpandParent"
      @select="onSelect"
      @check="onCheck"
      @expand="onExpand"
    >
      <template slot="title" slot-scope="record">
        <span v-if="record[replaceFields.title].indexOf(searchValue) > -1">
          {{
            record[replaceFields.title].substr(
              0,
              record[replaceFields.title].indexOf(searchValue)
            )
          }}
          <span style="color: #f50">{{ searchValue }}</span>
          {{
            record[replaceFields.title].substr(
              record[replaceFields.title].indexOf(searchValue) +
                searchValue.length
            )
          }}
        </span>
        <span v-else>
          {{ record[replaceFields.title] }}
        </span>

        <a-dropdown :trigger="['click']" style="margin-left:20px">
          <a class="ant-dropdown-link" @click.stop="e => e.preventDefault()">
            点击展开菜单 <a-icon type="down" />
          </a>
          <slot name="menu" slot="overlay" :record="record"></slot>
        </a-dropdown>
      </template>
    </a-tree>
  </div>
</template>
<script>
import { cloneDeep } from "lodash";

export default {
  props: {
    treeData: { type: Array, default: () => [] },
    checkable: { type: Boolean, default: false },
    multiple: { type: Boolean, default: false },
    defaultSelectedKeys: { type: Array, default: () => [] },
    replaceFields: {
      type: Object,
      default: () => {
        return {
          children: "children",
          title: "title",
          key: "key"
        };
      }
    }
  },
  data() {
    return {
      selectedKeys: this.defaultSelectedKeys,
      expandedKeys: [],
      searchValue: "",
      sTreeData: [],
      autoExpandParent: true
    };
  },
  watch: {
    treeData(val) {
      this.sTreeData = cloneDeep(val);
    }
  },
  methods: {
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys;
      this.$emit("selectedKeysChange", this.selectedKeys);
      this.$emit("selectedNodesChange", info.selectedNodes);
    },
    onCheck(checkedKeys, info) {
      this.$emit("checkedKeysChange", checkedKeys);
      this.$emit("checkedNodesChange", info.checkedNodes);
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.$emit("expandedKeysChange", expandedKeys);
    },
    addNode(key, obj) {
      this.add(key, this.sTreeData, obj);
    },
    add(key, tree, obj) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node[this.replaceFields.key] === key) {
          console.log("添加");
          if (!node.children) {
            this.$set(node, "children", []);
          }
          node.children.push(obj);

          this.selectedKeys.push(obj[this.replaceFields.key]);
          this.$emit("selectedKeysChange", this.selectedKeys);
          this.expandedKeys.push(node[this.replaceFields.key]);
          this.$emit("expandedKeysChange", this.expandedKeys);
          break;
        } else if (node.children) {
          this.add(key, node.children, obj);
        }
      }
    },
    delNode(key) {
      this.del(key, this.sTreeData);
    },
    del(key, tree) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node[this.replaceFields.key] === key) {
          console.log("删除");
          tree.splice(i, 1);
        } else if (node.children) {
          this.del(key, node.children);
        }
      }
    },
    editNode(key, obj) {
      this.edit(key, this.sTreeData, obj);
    },
    edit(key, tree, obj) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node[this.replaceFields.key] === key) {
          console.log("编辑");
          this.$set(tree, i, obj);
          break;
        } else if (node.children) {
          this.edit(key, node.children, obj);
        }
      }
    },
    getNodeByKey(key) {
      return this.get(key, this.sTreeData);
    },
    get(key, tree) {
      let result;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node[this.replaceFields.key] === key) {
          // console.log('找到')
          result = node;
          break;
        } else if (
          node[this.replaceFields.children] &&
          this.get(key, node.children)
        ) {
          result = this.get(key, node.children);
        }
      }
      return result;
    },
    getParentKeyByKey(key) {
      let res = this.getParentNodeByKey(key, this.sTreeData);
      if (res) {
        return res[this.replaceFields.key];
      } else {
        return null;
      }
    },
    getParentNodeByKey(key, tree) {
      let parentNode;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node[this.replaceFields.children]) {
          if (
            node[this.replaceFields.children].some(
              item => item[this.replaceFields.key] === key
            )
          ) {
            parentNode = node;
          } else if (this.getParentNodeByKey(key, node.children)) {
            parentNode = this.getParentNodeByKey(key, node.children);
          }
        }
      }
      return parentNode;
    },
    // 根据title关键字，获取keys
    getKeysByTitle(title, tree) {
      let vm = this;
      let keys = [];
      function getKeysByTitle(title, tree) {
        for (let i = 0; i < tree.length; i++) {
          const element = tree[i];
          if (element[vm.replaceFields.title].indexOf(title) !== -1) {
            keys.push(element[vm.replaceFields.key]);
          } else if (element[vm.replaceFields.children]) {
            keys.concat(
              getKeysByTitle(title, element[vm.replaceFields.children])
            );
          }
        }
      }
      getKeysByTitle(title, tree);
      return keys;
    },

    // 根据title关键字展开树
    onExpandTreeByTitle(title) {
      if (title.trim() === "") {
        this.expandedKeys = [];
        this.autoExpandParent = false;
      } else {
        this.autoExpandParent = true;
        this.searchValue = title;
        let keys = this.getKeysByTitle(title, this.sTreeData);
        this.expandedKeys = keys;
      }
    },
    getKeysBySearch(key, tree) {
      let keys = [];
      let vm = this;
      function getKeyBySearch(key, tree) {
        for (let i = 0; i < tree.length; i++) {
          let node = tree[i];
          if (node[vm.replaceFields.key].indexOf(key) !== -1) {
            keys.push(node[[vm.replaceFields.key]]);
          }
          if (node[vm.replaceFields.children]) {
            getKeyBySearch(key, node[vm.replaceFields.children]);
          }
        }
      }
      getKeyBySearch(key, tree);
      return keys;
    },
    // 根据key展开树
    onExpandTreeByKey(key) {
      let res = this.getKeysBySearch(key, this.sTreeData);
      console.log(res);
    },
    onChange(e) {
      const value = e.target.value;
      // this.onExpandTreeByTitle(value)
      this.onExpandTreeByKey(value);
    }
  }
};
</script>
